'use strict';

const { log } = require('console');

const db = uniCloud.database()
const $ = db.command.aggregate
const _ = db.command

exports.main = async (event, context) => {
  console.log('\n================== 云函数入口 ==================')
  console.log('接收参数:', {
    action: event.action,
    params: event.params
  })

  const { action, params = {} } = event

  switch (action) {
    case 'test':
      return await testApi(params)

    case 'getCompanyPatentInfo':
      return await getCompanyPatentInfo(params)

    case 'getPatentDetail':
      return await getPatentDetail(params)

    case 'getHotCompanies':
      return await getHotCompanies(params)

    default:
      return {
        code: 404,
        msg: '未找到对应的操作'
      }
  }
}

// 将测试代码移到这里
async function testApi(params) {
  console.log('开始API测试 ====================')

  const TEST_COMPANY = '平安银行股份有限公司'
  const TEST_STOCK_CODE = '000001.SZ'

  try {
    // 测试初始化专利统计
    console.log('\n测试3: 初始化专利统计')
    console.log('参数:', {
      companyName: TEST_COMPANY,
      stockCode: TEST_STOCK_CODE
    })

    const initResult = await initializePatentStats({
      companyName: TEST_COMPANY,
      stockCode: TEST_STOCK_CODE
    })

    console.log('初始化结果:', JSON.stringify(initResult, null, 2))

    return {
      code: 200,
      msg: 'ok',
      data: {
        initResult
      }
    }

  } catch (e) {
    console.error('测试异常:', e)
    return {
      code: 500,
      msg: '测试失败:' + e.message
    }
  } finally {
    console.log('测试完成 ====================')
  }
}

// 获取公司专利信息主函数
async function getCompanyPatentInfo({ stockCode }) {
  console.log('获取公司专利信息:', stockCode)

  try {
    // 1. 获取公司基本信息
    const companyInfo = await db.collection('a_stocks')
      .where({
        stock_code: stockCode
      })
      .field({
        name: true,
        fullname: true,
        industry: true,
        area: true
      })
      .get()

    if (!companyInfo.data.length) {
      return {
        code: 404,
        msg: '未找到公司信息'
      }
    }

    // 2. 检查专利统计状态
    const statsInfo = await checkPatentStats(stockCode)
    console.log('专利统计状态:', statsInfo)

    // 3. 如果有统计记录,初始化一次
    if (!statsInfo.exists) {
      console.log('首次访问,开始初始化专利数据...')
      const initResult = await initializePatentStats({
        companyName: companyInfo.data[0].fullname,
        stockCode
      })
      console.log('initResult', initResult)
      if (!initResult) {
        return {
          code: 500,
          msg: '初始化专利数据失败:' + initResult.error
        }
      }

      statsInfo.stats = initResult.data
    } else {
      // 4. 更新访问计数并检查是否需要增量更新
      const visitResult = await updateVisitCount(stockCode)
      console.log('访问计数更新结果:', visitResult)

      if (visitResult.needsUpdate) {
        console.log('需要增量更新...')
        const updateResult = await incrementalUpdate({
          stockCode,
          companyName: companyInfo.data[0].fullname
        })

        if (updateResult.success) {
          statsInfo.stats = updateResult.data
        }
      }
    }

    // 5. 格式化返回数据
    return {
      code: 200,
      msg: 'ok',
      data: {
        // 基本信息
        basicInfo: {
          totalCount: statsInfo.stats.total_count,
          sampledCount: statsInfo.stats.sampled_count,
          samplingInfo: {
            sampleSize: statsInfo.stats.patent_stats.sample_info.sample_size,
            totalSize: statsInfo.stats.patent_stats.sample_info.total_size,
            samplingRate: statsInfo.stats.patent_stats.sample_info.sampling_rate,
            completeness: statsInfo.stats.patent_stats.sample_info.completeness,
            samplingConfidence: statsInfo.stats.patent_stats.sample_info.sampling_confidence,
            lastUpdate: statsInfo.stats.patent_stats.sample_info.last_update
          }
        },

        // 公司信息
        companyInfo: {
          name: companyInfo.data[0].name,
          fullname: companyInfo.data[0].fullname,
          industry: companyInfo.data[0].industry,
          area: companyInfo.data[0].area
        },

        // 专利统计
        patentStats: {
          // 专利类型分布
          typeDistribution: {
            sampled: statsInfo.stats.patent_stats.type_distribution.sampled,
            estimated: statsInfo.stats.patent_stats.type_distribution.estimated
          },

          // 年度分布
          yearDistribution: {
            total: statsInfo.stats.patent_stats.year_distribution.total,
            trend: statsInfo.stats.patent_stats.year_distribution.trend,
            summary: statsInfo.stats.patent_stats.year_distribution.summary
          },

          // IPC类分布
          ipcDistribution: {
            sampled: statsInfo.stats.patent_stats.ipc_distribution.sampled,
            estimated: statsInfo.stats.patent_stats.ipc_distribution.estimated
          },

          // 技术领域分布
          techFieldDistribution: {
            fields: statsInfo.stats.patent_stats.tech_field_distribution.fields
          }
        },

        // 抽样状态
        samplingStatus: {
          all: statsInfo.stats.sampling_status.all,
          year: statsInfo.stats.sampling_status.year
        },

        // 更新信息
        updateInfo: {
          lastUpdate: statsInfo.stats.last_update_time,
          apiCallCount: statsInfo.stats.api_call_count,
          createTime: statsInfo.stats.create_time,
          updateTime: statsInfo.stats.update_time
        }
      }
    }

  } catch (e) {
    console.error('获取专利信息异常:', e)
    return {
      code: 500,
      msg: '获取专利信息失败:' + e.message
    }
  }
}

// 检查专利统计状态
async function checkPatentStats(stockCode) {
  try {
    // 如果发现多条记录，保留最新的一条
    const stats = await db.collection('a_stock_patent_stats')
      .where({ stock_code: stockCode })
      .orderBy('update_time', 'desc')  // 按更新时间倒序
      .get()

    if (stats.data.length > 1) {
      console.log('发现多条记录，清理重复数据...')
      // 保留第一条（最新），删除其他的
      const deleteIds = stats.data
        .slice(1)
        .map(item => item._id)

      await db.collection('a_stock_patent_stats')
        .where({
          _id: db.command.in(deleteIds)
        })
        .remove()
    }

    if (!stats.data.length) {
      return {
        exists: false,
        stats: null
      }
    }

    // 更新访问计数
    await db.collection('a_stock_patent_stats')
      .where({ stock_code: stockCode })
      .update({
        api_call_count: db.command.inc(1)
      })

    return {
      exists: true,
      stats: stats.data[0]
    }

  } catch (e) {
    console.error('检查专利统计状态异常:', e)
    throw e
  }
}

// 初始化公司专利统计数据
async function initializePatentStats(params) {
  console.log('\n================== 初始化专利统计 ==================')
  console.log('初始化参数:', params)

  const { stockCode, companyName } = params

  if (!stockCode || !companyName) {
    return {
      success: false,
      error: '缺少必要参数'
    }
  }

  try {
    const api = require('./libs/patentApi.js')

    // 1. 并发获取专利总数和各年份数据
    console.log('\n1. 开始获取专利数据...')
    const currentYear = new Date().getFullYear()
    const years = Array.from(
      { length: 5 },
      (_, i) => currentYear - i
    )

    // 构建所有请求任务
    const tasks = [
      api.getPatentTotal(companyName, stockCode),
      ...years.map(year =>
        api.getPatentList({
          companyName,
          stockCode,
          startDate: `${year}-01-01`,
          endDate: `${year}-12-31`,
          pageNum: 1,
          pageSize: 20
        })
      )
    ]

    // 并发执行所有请求
    const [totalResult, ...yearResults] = await Promise.all(tasks)

    console.log('数据请求完成')
    console.log('总数据结果:', {
      success: totalResult.success,
      total: totalResult.total,
      dataCount: totalResult.data?.length
    })

    // 处理无数据的情况
    if (!totalResult.success || totalResult.total === 0) {
      // 创建空的统计记录
      const emptyStatsData = {
        stock_code: stockCode,
        total_count: 0,
        sampled_count: 0,
        api_call_count: 1,

        sampling_status: {
          all: {
            total: 0,
            sampled: 0,
            pages_fetched: [],
            last_page: 0,
            direction: 'desc',
            last_sample_time: new Date()
          },
          year: Object.fromEntries(
            years.map(year => [
              year,
              {
                total: 0,
                sampled: 0,
                pages_fetched: []
              }
            ])
          )
        },

        patent_stats: {
          sample_info: {
            sample_size: 0,
            total_size: 0,
            sampling_rate: 0,
            completeness: 0,
            sampling_confidence: 0,
            last_update: new Date()
          },

          type_distribution: {
            sampled: [],
            estimated: []
          },

          ipc_distribution: {
            sampled: [],
            estimated: []
          },

          year_distribution: {
            total: 0,
            trend: years.map(year => ({
              year,
              count: 0,
              growth_rate: 0,
              percentage: 0
            })),
            summary: {
              max_year: currentYear,
              max_count: 0,
              avg_yearly_count: 0
            }
          },

          tech_field_distribution: {
            fields: []
          }
        },

        last_update_time: new Date(),
        create_time: new Date(),
        update_time: new Date()
      }

      // 保存空统计记录
      try {
        const existingStats = await db.collection('a_stock_patent_stats')
          .where({ stock_code: stockCode })
          .get()

        if (existingStats.data.length > 0) {
          await db.collection('a_stock_patent_stats')
            .doc(existingStats.data[0]._id)
            .update(emptyStatsData)
        } else {
          await db.collection('a_stock_patent_stats')
            .add(emptyStatsData)
        }

        return {
          success: true,
          data: emptyStatsData
        }
      } catch (e) {
        console.error('保存空统计记录失败:', e)
        throw e
      }
    }

    // 有数据的情况继续原有逻辑
    // ... 保持原有代码不变 ...
    console.log('年度数据结果:', yearResults.map((r, i) => ({
      year: years[i],
      success: r.success,
      total: r.total,
      dataCount: r.data?.length
    })))


    // 2. 保存所有专利数据
    console.log('\n2. 开始保存专利数据...')
    console.log('处理最新专利数据, 数量:', totalResult.data.length)

    // 初始化变量
    const allPatentDetails = []
    const yearlyStats = {}  // 只在这里声明一次

    // 添加最新专利数据
    allPatentDetails.push(...totalResult.data.map(item => ({
      stock_code: stockCode,
      patentNum: item.patentNum,
      title: item.title,
      patentType: item.patentType,
      applicantname: item.applicantname,
      inventor: item.inventor || '',
      applicationTime: new Date(item.applicationTime),
      pubDate: new Date(item.pubDate),
      grantDate: item.grantDate ? new Date(item.grantDate) : null,
      mainCatNum: item.mainCatNum,
      allCatNum: JSON.parse(item.allCatNum || '[]'),
      abstracts: item.abstracts || '',
      address: item.address || '',
      agency: item.agency || '',
      agent: item.agent || '',
      patentStatus: item.patentStatus,
      cat: item.cat,
      create_time: new Date(),
      update_time: new Date()
    })))

    // 处理年度数据
    yearResults.forEach((yearResult, index) => {
      const year = years[index]
      console.log(`处理${year}年数据...`)

      // 初始化该年份的统计数据(默认值为0)
      yearlyStats[year] = {
        count: 0,
        growth_rate: 0
      }

      // 检查数据有效性
      if (yearResult && yearResult.success && Array.isArray(yearResult.data)) {
        console.log(`${year}年数据有效, 数量:`, yearResult.data.length)
        // 更新年度统计数量
        yearlyStats[year].count = yearResult.total || 0

        // 只有在有实际数据时才添加到详情列表
        if (yearResult.data.length > 0) {
          allPatentDetails.push(...yearResult.data.map(item => ({
            stock_code: stockCode,
            patentNum: item.patentNum,
            title: item.title,
            patentType: item.patentType,
            applicantname: item.applicantname,
            inventor: item.inventor || '',
            applicationTime: new Date(item.applicationTime),
            pubDate: new Date(item.pubDate),
            grantDate: item.grantDate ? new Date(item.grantDate) : null,
            mainCatNum: item.mainCatNum,
            allCatNum: JSON.parse(item.allCatNum || '[]'),
            abstracts: item.abstracts || '',
            address: item.address || '',
            agency: item.agency || '',
            agent: item.agent || '',
            patentStatus: item.patentStatus,
            cat: item.cat,
            create_time: new Date(),
            update_time: new Date()
          })))
        }
      } else {
        console.log(`${year}年无有效数据, 记录为0`)
      }
    })

    console.log('准备保存专利数据, 总数:', allPatentDetails.length)

    // 3. 构建年度统计
    console.log('\n3. 开始构建年度统计...')
    yearResults.forEach((yearResult, index) => {
      if (yearResult.success) {
        const year = years[index]
        yearlyStats[year] = {
          count: yearResult.total,
          growth_rate: 0
        }
      }
    })

    // 计算增长率
    const yearList = Object.keys(yearlyStats).sort()
    console.log('计算年度增长率...')
    console.log('原始年度数据:', yearlyStats)

    for (let i = 1; i < yearList.length; i++) {
      const currentYear = yearList[i]
      const prevYear = yearList[i - 1]
      const currentCount = yearlyStats[currentYear].count
      const prevCount = yearlyStats[prevYear].count

      yearlyStats[currentYear].growth_rate =
        prevCount === 0 ? 0 : ((currentCount - prevCount) / prevCount * 100).toFixed(2)
    }

    console.log('年度统计结果:', yearlyStats)

    // 4. 计算统计数据
    console.log('\n4. 开始计算统计数据...')
    const stats = calculatePatentStats(allPatentDetails, totalResult.total)
    console.log('统计计算完成')

    // 5. 保存统计记录
    console.log('\n5. 开始保存统计记录...')
    const statsData = {
      stock_code: stockCode,
      total_count: totalResult.total,
      sampled_count: allPatentDetails.length,
      api_call_count: 1,

      // 抽样状态
      sampling_status: {
        all: {
          total: totalResult.total,
          sampled: allPatentDetails.length,
          pages_fetched: [1],
          last_page: 1,
          direction: 'desc',
          last_sample_time: new Date()
        },
        year: Object.fromEntries(
          years.map(year => [
            year,
            {
              total: yearlyStats[year]?.count || 0,
              sampled: yearResults[years.indexOf(year)]?.data.length || 0,
              pages_fetched: [1]
            }
          ])
        )
      },

      // 专利统计
      patent_stats: {
        // 抽信息
        sample_info: {
          sample_size: allPatentDetails.length,
          total_size: totalResult.total,
          sampling_rate: allPatentDetails.length / totalResult.total,
          completeness: 0.95,
          sampling_confidence: 0.95,
          last_update: new Date()
        },

        // 专利类型分布 - 修改为数组格式
        type_distribution: {
          sampled: [
            {
              type: "发明专利",
              count: stats.type_distribution.sampled["发明专利"] || 0,
              percentage: parseFloat(((stats.type_distribution.sampled["发明专利"] || 0) / allPatentDetails.length * 100).toFixed(2))
            },
            {
              type: "实用新型",
              count: stats.type_distribution.sampled["实用新型"] || 0,
              percentage: parseFloat(((stats.type_distribution.sampled["实用新型"] || 0) / allPatentDetails.length * 100).toFixed(2))
            },
            {
              type: "外观专利",
              count: (stats.type_distribution.sampled["外观设计"] || 0) + (stats.type_distribution.sampled["外观专利"] || 0),
              percentage: parseFloat((((stats.type_distribution.sampled["外观设计"] || 0) + (stats.type_distribution.sampled["外观专利"] || 0)) / allPatentDetails.length * 100).toFixed(2))
            }
          ],
          estimated: [
            {
              type: "发明专利",
              count: Math.round((stats.type_distribution.sampled["发明专利"] || 0) / (allPatentDetails.length / totalResult.total)),
              percentage: parseFloat(((stats.type_distribution.sampled["发明专利"] || 0) / allPatentDetails.length * 100).toFixed(2))
            },
            {
              type: "实用新型",
              count: Math.round((stats.type_distribution.sampled["实用新型"] || 0) / (allPatentDetails.length / totalResult.total)),
              percentage: parseFloat(((stats.type_distribution.sampled["实用新型"] || 0) / allPatentDetails.length * 100).toFixed(2))
            },
            {
              type: "外观专利",
              count: Math.round(((stats.type_distribution.sampled["外观设计"] || 0) + (stats.type_distribution.sampled["外观专利"] || 0)) / (allPatentDetails.length / totalResult.total)),
              percentage: parseFloat((((stats.type_distribution.sampled["外观设计"] || 0) + (stats.type_distribution.sampled["外观专利"] || 0)) / allPatentDetails.length * 100).toFixed(2))
            }
          ]
        },

        // IPC分类分布 - 修改为数组格式
        ipc_distribution: {
          sampled: Object.entries(stats.ipc_distribution.sampled)
            .map(([code, data]) => ({
              code,
              name: data.name,
              count: data.count,
              percentage: parseFloat((data.count / allPatentDetails.length * 100).toFixed(2))
            }))
            .sort((a, b) => b.count - a.count), // 按数量降序排序
          estimated: Object.entries(stats.ipc_distribution.sampled)
            .map(([code, data]) => ({
              code,
              name: data.name,
              count: Math.round(data.count / (allPatentDetails.length / totalResult.total)),
              percentage: parseFloat((data.count / allPatentDetails.length * 100).toFixed(2))
            }))
            .sort((a, b) => b.count - a.count) // 按数量降序排序
        },

        // 年份分���
        year_distribution: {
          total: totalResult.total,
          trend: Object.entries(yearlyStats)
            .map(([year, data]) => ({
              year,
              count: data.count,
              growth_rate: parseFloat(data.growth_rate),
              percentage: parseFloat((data.count / totalResult.total * 100).toFixed(2))
            }))
            .sort((a, b) => b.year - a.year), // 按年份降序排序
          summary: {
            max_year: Object.keys(yearlyStats).reduce((a, b) => yearlyStats[a].count > yearlyStats[b].count ? a : b),
            max_count: Math.max(...Object.values(yearlyStats).map(data => data.count)),
            avg_yearly_count: parseFloat((Object.values(yearlyStats).reduce((sum, data) => sum + data.count, 0) / Object.keys(yearlyStats).length).toFixed(2))
          }
        },

        // 技术领域分布 - 修改为数组格式
        tech_field_distribution: {
          fields: Object.entries(stats.tech_field_distribution.fields)
            .map(([name, data]) => ({
              name,
              count: data.count,
              percentage: parseFloat((data.count / allPatentDetails.length * 100).toFixed(2)),
              main_ipc: data.main_ipc,
              related_ipcs: Array.from(data.related_ipcs || [])
            }))
            .sort((a, b) => b.count - a.count) // 按数量降序排序
        }
      },

      last_update_time: new Date(),
      create_time: new Date(),
      update_time: new Date()
    }


    try {
      // 先查询是否存在记录
      const existingStats = await db.collection('a_stock_patent_stats')
        .where({
          stock_code: stockCode
        })
        .get()

      let result
      if (existingStats.data.length > 0) {
        // 如果存在则更新
        console.log('更新已存在的统计记录')
        result = await db.collection('a_stock_patent_stats')
          .doc(existingStats.data[0]._id)
          .update(statsData)
      } else {
        // 如果不存在则增
        console.log('创建新的统计记录')
        result = await db.collection('a_stock_patent_stats')
          .add(statsData)
      }

      console.log('保存统计记录结果:', result)
      console.log('初始化完成 ====================')

      return {
        success: true,
        data: statsData
      }
    } catch (e) {
      console.error('保存统计记录失败:', e)
      throw e
    }

  } catch (e) {
    console.error('初始化专利统计异常:', e)
    return {
      success: false,
      error: e.message || '初始化失败'
    }
  }
}

// 计算专利统计数据
function calculatePatentStats(patents, totalCount) {
  console.log('\n================== 计算专利统计 ==================')
  console.log('输入数据:', {
    样本数: patents.length,
    总数: totalCount
  })

  // 添加数据验证
  const validPatents = patents.filter(patent => {
    const isValid = patent && patent.patentNum && patent.patentType
    if (!isValid) {
      console.warn('发现无效专利数据:', patent)
    }
    return isValid
  })

  console.log('有效专利数据:', validPatents.length)

  // 1. 专利类型分布
  console.log('\n1. 计算专利类型分布...')
  const typeCount = {
    '发明专利': 0,
    '实用新型': 0,
    '外观专利': 0
  }

  validPatents.forEach(patent => {
    if (patent.patentType === '外观设计' || patent.patentType === '外观专利') {
      typeCount['外观专利']++
    } else if (patent.patentType) {
      if (!typeCount.hasOwnProperty(patent.patentType)) {
        console.warn('发现未知专利类型:', patent.patentType)
      }
      typeCount[patent.patentType]++
    }
  })

  console.log('专利类型统计结果:', typeCount)

  // 2. IPC分类分布
  console.log('\n2. 计算IPC分类分布...')
  const ipcCount = {}
  validPatents.forEach(patent => {
    if (patent.mainCatNum) {
      const mainCat = patent.mainCatNum.substring(0, 3)
      if (!ipcCount[mainCat]) {
        ipcCount[mainCat] = {
          count: 0,
          name: mainCat  // 暂时使用编码作为名称
        }
      }
      ipcCount[mainCat].count++
    }
  })

  console.log('IPC分类统计完成')

  // 3. 技术领域分布
  console.log('\n3. 计算技术领域分布...')
  const techFields = {}
  validPatents.forEach(patent => {
    if (patent.cat) {
      const field = patent.cat.replace(/;$/, '')
      if (!techFields[field]) {
        techFields[field] = {
          count: 0,
          main_ipc: patent.mainCatNum?.substring(0, 3) || '',
          related_ipcs: new Set()
        }
      }
      techFields[field].count++
      if (patent.mainCatNum) {
        const ipcCode = patent.mainCatNum.substring(0, 4)
        if (ipcCode) {
          techFields[field].related_ipcs.add(ipcCode)
        }
      }
    }
  })

  console.log('技术领域统计完成')
  console.log('统计计算完成 ====================')
  return {
    type_distribution: { sampled: typeCount },
    ipc_distribution: { sampled: ipcCount },
    tech_field_distribution: { fields: techFields }
  }
}

// 修改保存专利详情的函数
async function savePatentDetails(details) {
  console.log('\n================== 保存专利详情 ==================')
  console.log('待保存数据数量:', details.length)

  try {
    // 使用 upsert 操作批量处理所有记录
    const result = await db.collection('a_patent_details')
      .where({
        patentNum: db.command.in(details.map(p => p.patentNum))
      })
      .update({
        data: details,
        multi: true,
        upsert: true
      })

    console.log('保存结果:', result)
    console.log('专利数据保存完成 ====================')
    return true

  } catch (e) {
    console.error('保存专利数据失败:', e)
    throw e
  }
}

// 更新访问计数
async function updateVisitCount(stockCode) {
  console.log('更新访问计数:', stockCode)

  try {
    // 1. 更新访问次数
    const updateResult = await db.collection('a_stock_patent_stats')
      .where({ stock_code: stockCode })
      .update({
        api_call_count: db.command.inc(1),
        update_time: new Date()
      })

    // 2. 获取更新后的统计数据
    const stats = await db.collection('a_stock_patent_stats')
      .where({ stock_code: stockCode })
      .get()

    if (!stats.data.length) {
      throw new Error('统计记录不存在')
    }

    const currentStats = stats.data[0]

    // 3. 判断是否需要增量更新
    // 每访问10次进行一次增量更新
    const needsUpdate = currentStats.api_call_count % 10 === 0

    return {
      success: true,
      newCount: currentStats.api_call_count,
      needsUpdate,
      stats: currentStats
    }

  } catch (e) {
    console.error('更新访问计数异常:', e)
    return {
      success: false,
      error: e.message
    }
  }
}

// 增量更新函数
async function incrementalUpdate({ stockCode, companyName }) {
  try {
    const api = require('./libs/patentApi.js')

    // 1. 获取当前统计状态
    const currentStats = await db.collection('a_stock_patent_stats')
      .where({ stock_code: stockCode })
      .get()
      .then(res => res.data[0])

    // 2. 获取已抓取的页码
    const fetchedPages = currentStats.sampling_status.all.pages_fetched
    let nextPage = Math.max(...fetchedPages) + 1

    // 3. 获取新的专利数据
    const result = await api.getPatentList({
      companyName,
      stockCode,
      pageNum: nextPage,
      pageSize: 20
    })

    if (!result.success) {
      throw new Error('获取专利数据失败: ' + result.error)
    }

    // 4. 保存新专利数据
    if (result.data.length > 0) {
      const formattedPatents = result.data.map(item => ({
        stock_code: stockCode,
        patentNum: item.patentNum,
      }))
      await savePatentDetails(formattedPatents)
    }

    // 5. 更新统计状态
    const updateData = {
      'sampling_status.all.pages_fetched': db.command.push(nextPage),
      'sampling_status.all.last_page': nextPage,
      'sampling_status.all.last_sample_time': new Date(),
      update_time: new Date()
    }

    await db.collection('a_stock_patent_stats')
      .where({ stock_code: stockCode })
      .update(updateData)

    // 6. 启动后台任务重新计算统计数据
    uniCloud.callFunction({
      name: 'recalculateStats',
      data: { stockCode }
    })

    return { success: true }

  } catch (e) {
    console.error('增量更新异常:', e)
    return { success: false, error: e.message }
  }
}

// 添加获取专利详情的函数
async function getPatentDetail({ patentNum }) {
  try {
    if (!patentNum) {
      return {
        code: 400,
        msg: '缺少专利号'
      }
    }

    const detail = await db.collection('a_patent_details')
      .where({ patentNum })
      .get()
      .then(res => res.data[0])

    if (!detail) {
      return {
        code: 404,
        msg: '未找到专利信息'
      }
    }

    return {
      code: 200,
      msg: 'ok',
      data: {
        basicInfo: {
          patentNum: detail.patentNum,
          title: detail.title,
          patentType: detail.patentType,
          applicantname: detail.applicantname,
          inventor: detail.inventor,
          applicationTime: detail.applicationTime,
          pubDate: detail.pubDate,
          grantDate: detail.grantDate
        },
        technicalInfo: {
          mainCatNum: detail.mainCatNum,
          allCatNum: detail.allCatNum,
          abstracts: detail.abstracts,
          cat: detail.cat
        },
        otherInfo: {
          address: detail.address,
          agency: detail.agency,
          agent: detail.agent,
          patentStatus: detail.patentStatus
        }
      }
    }
  } catch (e) {
    console.error('获取专利详情异常:', e)
    return {
      code: 500,
      msg: '获取专利详情失败:' + e.message
    }
  }
}

// 添加获取热搜公司列表的函数
async function getHotCompanies({ limit = 20 } = {}) {
  try {
    // 1. 获取访问次数最多的公司统计记录
    const statsResult = await db.collection('a_stock_patent_stats')
      .orderBy('api_call_count', 'desc')
      .limit(limit)
      .get()

    if (!statsResult.data.length) {
      return {
        code: 200,
        msg: 'ok',
        data: { list: [] }
      }
    }

    // 2. 获取这些公司的基本信息
    const stockCodes = statsResult.data.map(item => item.stock_code)
    const companiesResult = await db.collection('a_stocks')
      .where({
        stock_code: db.command.in(stockCodes)
      })
      .field({
        stock_code: true,
        name: true,
        fullname: true,
        industry: true,
        area: true
      })
      .get()

    // 3. 将公司信息和专利统计信息合并
    const companyMap = new Map(
      companiesResult.data.map(item => [item.stock_code, item])
    )

    const list = statsResult.data.map(stats => {
      const company = companyMap.get(stats.stock_code) || {}
      return {
        stockCode: stats.stock_code,
        name: company.name || '',
        fullname: company.fullname || '',
        industry: company.industry || '',
        area: company.area || '',
        patentCount: stats.total_count || 0,
        sampledCount: stats.sampled_count || 0,
        visitCount: stats.api_call_count || 0,
        lastUpdate: stats.update_time
      }
    })

    return {
      code: 200,
      msg: 'ok',
      data: { list }
    }

  } catch (e) {
    console.error('获取热搜公司列表异常:', e)
    return {
      code: 500,
      msg: '获取热搜公司列表失败:' + e.message
    }
  }
}